// ==UserScript==
// @name         溜溜梅增强版
// @namespace    https://codeberg.org/canqing/TampermonVi
// @version      2025-04-30
// @description  点击复制，提取日期，分页加载功能，检查所有日期
// @author       Vi
// @match        *.liuliumei.com:8011/*
// @icon         https://www.google.com/s2/favicons?sz=64&domain=liuliumei.com
// @grant        GM_setClipboard
// @grant        GM_addStyle
// @grant        GM.xmlHttpRequest
// @connect      one.liuliumei.com
// @updateURL    https://gitee.com/canqing86/tampermon/raw/master/liuliumei.user.js
// @downloadURL  https://gitee.com/canqing86/tampermon/raw/master/liuliumei.user.js
// ==/UserScript==

(function() {
    'use strict';

    // 添加全局样式
    GM_addStyle(`
        .llm-button-container {
            position: fixed;
            top: 20px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 9999;
            display: flex;
            gap: 8px;
            flex-wrap: wrap;
            justify-content: center;
        }
        .llm-action-btn {
            background: #FF69B4;
            color: white;
            padding: 10px 20px;
            font-size: 14px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            min-width: 100px;
        }
    `);

    // 判断是否在目标页面
    function isTargetPage() {
        return window.location.pathname.includes('OutWareHouseListCodeInfo.aspx') ||
            window.location.pathname.includes('OutWareHouseListInfo.aspx');
    }

    // 创建按钮容器（新增检查所有日期按钮）
    function createButtons() {
        const container = document.createElement('div');
        container.className = 'llm-button-container';

        const buttonsHTML = window.location.pathname.includes('OutWareHouseListInfo.aspx') ?
              `<button class="llm-action-btn" id="llmCheckAllDates">检查所有日期</button>` :
        `<button class="llm-action-btn" id="llmCopy">复制箱码</button>
             <button class="llm-action-btn" id="llmShowAll">一页显示</button>
             <button class="llm-action-btn" id="llmViewDate">查看日期</button>`;

        container.innerHTML = buttonsHTML;
        return container;
    }


    // 核心功能函数 -------------------------------------------------

    // 复制箱码功能
    async function handleCopy() {
        try {
            const codes = Array.from(document.querySelectorAll('#ctl00_ContentPlaceHolder1_gridView td:nth-child(4)'))
            .map(td => td.textContent.trim())
            .filter(Boolean)
            .join('\n');

            if (!codes) throw new Error("未找到箱码数据");

            GM_setClipboard(codes, 'text');
            alert(`已复制 ${codes.split('\n').length} 条箱码`);
        } catch (error) {
            console.error('复制失败:', error);
            alert(`操作失败: ${error.message}`);
        }
    }

    // 查看日期功能
    function handleViewDate() {
        try {
            const dateMap = new Map();

            document.querySelectorAll('#ctl00_ContentPlaceHolder1_gridView td:nth-child(4)').forEach(td => {
                const code = td.textContent.trim();
                const datePart = code.split(' ')[1].substring(4, 10); // 提取日期段
                dateMap.set(datePart, (dateMap.get(datePart) || 0) + 1);
            });

            const report = Array.from(dateMap)
            .sort((a, b) => b[1] - a[1])
            .map(([date, count]) => `日期：${date} - ${count}次`)
            .join('\n');

            alert(`📅 日期统计：\n\n${report}`);
        } catch (error) {
            console.error('日期统计失败:', error);
            alert(`操作失败: ${error.message}`);
        }
    }

    // 分页加载功能（修复版）
    async function handleShowAll() {
        try {
            const pager = document.querySelector("#ctl00_ContentPlaceHolder1_gridView tr:last-child");
            if (!pager) throw new Error("找不到分页控件");

            const pageCount = parseInt(pager.querySelector("[id$='_LabelPageCount']").textContent);
            if (pageCount <= 1) return alert("已经是最后一页");

            // 加载提示
            const loading = document.createElement('div');
            loading.textContent = '正在加载数据...';
            Object.assign(loading.style, {
                position: 'fixed',
                top: '60px',
                left: '50%',
                transform: 'translateX(-50%)',
                background: 'yellow',
                padding: '10px',
                zIndex: 99999
            });
            document.body.appendChild(loading);

            // 分页请求（修正页码参数）
            for (let page = 2; page <= pageCount; page++) {
                loading.textContent = `正在加载第 ${page}/${pageCount} 页...`;

                // 关键修正：txtNewPageIndex应为当前页码-1（因页码从0开始）
                const targetPageIndex = page - 1;

                const formData = new URLSearchParams();
                formData.append('__EVENTTARGET', 'ctl00$ContentPlaceHolder1$gridView$ctl23$LinkButtonNextPage');
                formData.append('__VIEWSTATE', document.getElementById("__VIEWSTATE").value);
                formData.append('__VIEWSTATEGENERATOR', document.getElementById("__VIEWSTATEGENERATOR").value);
                formData.append('ctl00$ContentPlaceHolder1$gridView$ctl23$txtNewPageIndex', targetPageIndex); // 修正参数

                const response = await fetch(window.location.href, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded',
                        'Cookie': `ASP.NET_SessionId=${getSessionId()}`
                },
                body: formData
            });

            // 解析并更新VIEWSTATE（关键修正）
            const parser = new DOMParser();
            const doc = parser.parseFromString(await response.text(), 'text/html');
            const newViewState = doc.getElementById("__VIEWSTATE").value;
            const newViewStateGenerator = doc.getElementById("__VIEWSTATEGENERATOR").value;

            // 更新全局VIEWSTATE
            document.getElementById("__VIEWSTATE").value = newViewState;
            document.getElementById("__VIEWSTATEGENERATOR").value = newViewStateGenerator;

            // 插入数据
            const newRows = doc.querySelectorAll('#ctl00_ContentPlaceHolder1_gridView tr:not(:first-child):not(:last-child)');
            newRows.forEach(row => {
                document.querySelector('#ctl00_ContentPlaceHolder1_gridView tbody').appendChild(
                    document.importNode(row, true)
                );
            });
        }

        loading.remove();
        pager.remove();
        alert(`已加载全部 ${pageCount} 页数据`);
    } catch (error) {
        console.error('分页加载失败:', error);
        alert(`操作失败: ${error.message}`);
    }
}




    // 分页加载并收集日期数据（修改版）
    async function processPagination(url, orderId, proCode) {
        let allDates = [];

        try {
            // 初始请求
            const firstPageResponse = await GM.xmlHttpRequest({
                method: "GET",
                url: url,
                headers: {
                    "Cookie": `ASP.NET_SessionId=${getSessionId()}`
                }
            });

            let doc = new DOMParser().parseFromString(firstPageResponse.responseText, "text/html");
            let viewState = doc.getElementById("__VIEWSTATE").value;
            let viewStateGenerator = doc.getElementById("__VIEWSTATEGENERATOR").value;

            // 处理第一页数据
            allDates.push(...extractDatesFromDoc(doc));

            // 获取总页数
            const pageCount = parseInt(doc.querySelector("[id$='_LabelPageCount']")?.textContent || "1");
            if (pageCount <= 1) return allDates;

            // 分页请求
            for (let page = 2; page <= pageCount; page++) {
                const formData = new URLSearchParams();
                formData.append('__EVENTTARGET', 'ctl00$ContentPlaceHolder1$gridView$ctl23$LinkButtonNextPage');
                formData.append('__VIEWSTATE', viewState);
                formData.append('__VIEWSTATEGENERATOR', viewStateGenerator);
                formData.append('ctl00$ContentPlaceHolder1$gridView$ctl23$txtNewPageIndex', page - 1);

                const response = await GM.xmlHttpRequest({
                    method: "POST",
                    url: url,
                    headers: {
                        "Content-Type": "application/x-www-form-urlencoded",
                        "Cookie": `ASP.NET_SessionId=${getSessionId()}`
                    },
                    data: formData.toString()
                });

                doc = new DOMParser().parseFromString(response.responseText, "text/html");
                viewState = doc.getElementById("__VIEWSTATE").value;
                viewStateGenerator = doc.getElementById("__VIEWSTATEGENERATOR").value;

                allDates.push(...extractDatesFromDoc(doc));
            }
        } catch (error) {
            console.error('分页处理失败:', error);
        }
        return allDates;
    }

    // 从文档中提取日期
    function extractDatesFromDoc(doc) {
        return Array.from(doc.querySelectorAll('#ctl00_ContentPlaceHolder1_gridView td:nth-child(4)'))
            .map(td => {
            const code = td.textContent.trim();
            return code.split(' ')[1]?.substring(4, 10);
        })
            .filter(Boolean);
    }

    // 统计日期数据
    function generateDateReport(dates) {
        const dateMap = new Map();
        dates.forEach(date => {
            dateMap.set(date, (dateMap.get(date) || 0) + 1);
        });

        return Array.from(dateMap)
            .sort((a, b) => b[1] - a[1])
            .map(([date, count]) => `${date}-${count}个`)
            .join('，');
    }

    // 主处理函数
    async function handleCheckAllDates() {
        try {
            const rows = Array.from(document.querySelectorAll('#ctl00_ContentPlaceHolder1_gridView tr:not(:first-child)'));
            const results = [];

            for (const row of rows) {
                const cells = row.querySelectorAll('td');
                const seq = cells[0].textContent.trim();
                const planQty = cells[4].textContent.trim();
                const outQty = cells[5].textContent.trim();
                const link = row.querySelector('a').href;

                const loading = document.createElement('div');
                loading.textContent = `正在处理第 ${seq} 项...`;
                Object.assign(loading.style, {
                    position: 'fixed',
                    top: '60px',
                    left: '50%',
                    transform: 'translateX(-50%)',
                    background: 'yellow',
                    padding: '10px',
                    zIndex: 99999
                });
                document.body.appendChild(loading);

                const dates = await processPagination(link);
                loading.remove();

                results.push({
                    seq,
                    planQty,
                    outQty,
                    report: generateDateReport(dates)
                });
            }

            // 生成报告
            const report = results.map(r =>
                                       `${r.seq}、${r.planQty}-${r.outQty}（${r.report}）`
            ).join('\n');

            alert(`📅 完整日期统计：\n\n${report}`);
        } catch (error) {
            console.error('检查所有日期失败:', error);
            alert(`操作失败: ${error.message}`);
        }
    }

    // 辅助函数 -----------------------------------------------------
    function getSessionId() {
        return document.cookie.match(/ASP\.NET_SessionId=([^;]+)/)?.[1] || '';
    }

    // 初始化逻辑 ---------------------------------------------------
    function init() {
        if (!isTargetPage()) return;

        const containerId = 'llmButtonContainer';
        if (!document.getElementById(containerId)) {
            const container = createButtons();
            container.id = containerId;
            document.body.appendChild(container);

            // 绑定新按钮事件
            const checkBtn = document.getElementById('llmCheckAllDates');
            if (checkBtn) {
                checkBtn.addEventListener('click', handleCheckAllDates);
            }

            // 原有按钮事件绑定
            const copyBtn = document.getElementById('llmCopy');
            if (copyBtn) copyBtn.addEventListener('click', handleCopy);

            const showAllBtn = document.getElementById('llmShowAll');
            if (showAllBtn) showAllBtn.addEventListener('click', handleShowAll);

            const viewDateBtn = document.getElementById('llmViewDate');
            if (viewDateBtn) viewDateBtn.addEventListener('click', handleViewDate);
        }
    }

    // 启动监听
    new MutationObserver(() => init()).observe(document.body, {
        childList: true,
        subtree: true
    });
    init();

})();